package adventure.commands;

import adventure.*;
import player.*;
import colour.ColourUtil;

/**
 *
 * @author Michael Hanns
 *
 */
public class Open extends AbstractCommand {

    public Open(Adventure a) {
        super(a, new String[] {"OPEN"});
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if(args.length == 1) {
            return "Open where?\nSyntax: open <direction>";
        } else if (args.length == 2 && Util.isDirection(args[1])) {
            return open(p, args[1].charAt(0));
        } else {
            return "That is not a valid direction!";
        }
    }

    private String open(Player player, char dir) {
        int x = player.x();
        int y = player.y();
        int z = player.z();

        if (!rooms.isBlocked(x, y, z, dir)) {
            if (!rooms.isLocked(x, y, z, dir)) {
                if (rooms.isClosed(x, y, z, dir)) {
                    rooms.open(x, y, z, dir);
                    out.broadcastLocalToPlayer(player,
                            ColourUtil.colourise(player.getName(), ColourUtil.magenta)
                            + " opens the "
                            + ColourUtil.colourise(Util.fillDir(dir), ColourUtil.yellow)
                            + " door.");

                    return "You open the "
                            + ColourUtil.colourise(Util.fillDir(dir), ColourUtil.yellow)
                            + " door.";
                } else {
                    return "That way isn't closed!";
                }
            } else {
                return "That door is locked!";
            }
        } else {
            return "That is not a valid direction!";
        }
    }
}
